package jscontrol

import (
	"MqttCloudProtocolServer/ProtocolServer/scriptmanager/modulelib"
	"errors"

	"github.com/dop251/goja"
	"github.com/wonderivan/logger"
)

//CreateRTDBModule CreateRTDBModule
func CreateRTDBModule(runtime *goja.Runtime) *goja.Object {
	content := new(RTDBModule)
	content.rtdbOperator = new(modulelib.RTDBOperator)
	jsTimer := runtime.NewObject()
	err := jsTimer.Set("Start", content.read)
	if err != nil {
		logger.Error(err)
		return nil
	}
	err = jsTimer.Set("Stop", content.write)
	if err != nil {
		logger.Error(err)
		return nil
	}
	content.jsTimer = jsTimer
	content.runtime = runtime
	return jsTimer
}

//RTDBModule RTDBModule
type RTDBModule struct {
	rtdbOperator *modulelib.RTDBOperator
	jsTimer      *goja.Object
	runtime      *goja.Runtime
}

func (_this *RTDBModule) read(call goja.FunctionCall) goja.Value {
	if len(call.Arguments) < 1 {
		return GetFromResAndErr(false, errors.New("参数长度错误"), _this.runtime)
	}
	tag, err := GetStringFromArgument(call.Argument(0))
	if err != nil {
		return GetFromResAndErr(false, err, _this.runtime)
	}
	time, value := _this.rtdbOperator.Read(tag)
	object := _this.runtime.NewObject()
	object.Set("time", time)
	object.Set("value", value)
	return object
}
func (_this *RTDBModule) write(call goja.FunctionCall) goja.Value {
	if len(call.Arguments) < 3 {
		return GetFromResAndErr(false, errors.New("参数长度错误"), _this.runtime)
	}
	tag, err := GetStringFromArgument(call.Argument(0))
	if err != nil {
		return GetFromResAndErr(false, err, _this.runtime)
	}
	value, err := GetInterfaceFromArgument(call.Argument(0))
	if err != nil {
		return GetFromResAndErr(false, err, _this.runtime)
	}
	dateTime, err := GetUInt64FromArgument(call.Argument(0))
	if err != nil {
		return GetFromResAndErr(false, err, _this.runtime)
	}
	res, err := _this.rtdbOperator.Write(tag, dateTime, value)
	return GetFromResAndErr(res, err, _this.runtime)
}
